package com.wn.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wn.entity.User;
import com.wn.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author Yellow Docker
 * @since 2023-02-21
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Value("${server.port}")
    private Integer port;

    @Autowired
    private IUserService userService;

    @GetMapping("{id}")
    public User findUserById(@PathVariable("id") Integer id) {

//        try {
//            Thread.sleep(5000);
//        } catch (InterruptedException e) {
//            throw new RuntimeException(e);
//        }

//        int a = 10 / 0;

        log.info("服务者的端口是:{}",port);
        return userService.getById(id);
    }

    @DeleteMapping("{id}")
    public String deleteUserById(@PathVariable("id") Integer id) {
        return userService.removeById(id) ? "success  delete" : "fail delete";
    }


    @PutMapping()
    public String updateUserById(@RequestBody User user) {
        return userService.updateById(user) ? "success  delete" : "fail delete";
    }

    @PostMapping()
    public String addUser(@RequestBody User user) {
        return userService.saveOrUpdate(user) ? "success  delete" : "fail delete";
    }

    @GetMapping("list")
    public List<User> findAll() {
        return userService.list();
    }

    @GetMapping("page/{currentPage}/{pageSize}")
    public Map<String,Object> findPage(
            @PathVariable("currentPage") Integer currentPage,
            @PathVariable("pageSize") Integer pageSize) {

        IPage<User> p = new Page<>(currentPage,pageSize);

        IPage<User> page = userService.page(p);
        long total = page.getTotal();
        List<User> users = page.getRecords();

        Map<String,Object> map = new HashMap<>();
        map.put("total",total);
        map.put("data",users);

        return  map;
    }

}

